import json
import os

import requests
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.tools import tool
from langchain.agents.output_parsers.tools import ToolsAgentOutputParser
from langchain.agents.format_scratchpad.tools import format_to_tool_messages
from langchain.agents import AgentExecutor

from src.Basic.tools.weather import get_weather

load_dotenv(override=True)


#定义模型
model = init_chat_model(model="deepseek-chat", model_provider="deepseek")
# 定义 天气查询 工具函数
tools = [get_weather]
llm_with_tools = model.bind_tools(tools)

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "你是天气助手，请根据用户的问题，给出相应的天气信息"),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ]
)

#手动调用的过程
# 直接代码调用
# 将工具绑定到模型
response = llm_with_tools.invoke("你好， 请问北京的天气怎么样？")
print(response)
# 解析模型响应
agentAction = ToolsAgentOutputParser().invoke(response)
print(agentAction)
for tool_call in response.tool_calls:
    selected_tool = {"get_weather": get_weather}[tool_call["name"].lower()]
    tool_output = selected_tool.invoke(tool_call["args"])
print(tool_output)
format_to_tool_messages(intermediate_steps = [(agentAction[0], tool_output)])
